<?php


namespace app\store\service\dealer;


class OrderExport
{

    /**
     * 订单导出
     * @param $list
     */
    public static function orderList($orders)
    {
        //表格标题
        $tileArray = [
            '订单号', '商品信息', '订单总价', '初级团长佣金', '高级团长佣金', '前团长佣金', '实际销售收入', '佣金结算'
        ];
        // 表格内容
        $dataArray = [];
        foreach ($orders as $order) {
            $dataArray[] = [
                '订单号' => self::filterValue($order['order_master']['order_no']),
                '商品信息' => self::filterGoodsInfo($order['order_master']),
                '订单总价' => self::filterValue($order['order_price']),
                '初级团长佣金' => self::filterValue($order['first_money']),
                '高级团长佣金' => self::filterValue($order['second_money']),
                '前团长佣金' => self::filterValue($order['third_money']),
                '实际销售收入' => self::filterValue(self::getIncome($order)),
                '佣金结算' => self::filterValue($order['is_settled'] ? '已结算' : '未结算')
            ];
        }
        // 导出csv文件
        $filename = 'order-' . date('YmdHis');
        return export_excel($filename . '.csv', $tileArray, $dataArray);
    }

    /**
     * 平台实际销售收入
     */
    private static function getIncome($order)
    {
        return $order['order_price'] - $order['first_money'] - $order['second_money'] - $order['third_money'];
    }

    /**
     * 格式化商品信息
     * @param $order
     * @return string
     */
    private static function filterGoodsInfo($order)
    {
        $content = '';
        foreach ($order['goods'] as $key => $goods) {
            $price = $goods['total_price'] / $goods['total_num'];
            $content .= ($key + 1) . ".商品名称：{$goods['goods_name']}\n";
            !empty($goods['goods_attr']) && $content .= "　商品规格：{$goods['goods_attr']}\n";
            $content .= "  单价：{$price}\n";
            $content .= "　购买数量：{$goods['total_num']}\n";
            $content .= "　商品总价：{$goods['total_price']}元\n\n";
        }
        return $content;
    }

    /**
     * 表格值过滤
     * @param $value
     * @return string
     */
    private static function filterValue($value)
    {
        return "\t" . $value . "\t";
    }


}